/**
 * Created by Administrator on 2017/1/15.
 */

var config = require('./config');

var MJ = require('../MJ/MJ');
var MJRoom = require('../MJ/room').MJRoom;

var Const = require('./const');
var SubCode = require('../subCode');


exports.WWMJRoom = MJRoom.extend({

    baoCard: 0,                 //混牌
    _jingCard: 0,                 //金牌
    _playcard: 0,
    _LaZhuangStatus : 0,

    init: function (rid, creator, msg) {
        this._super(rid, creator, msg);

        this.baoCard = 0;
        this._playcard = 0;
        this._jingCard = 0;
        this._LaZhuangStatus = Const.LaZhuangStatus.NONE;
        this.setSaveReplay(true);

    },
    checkInit: function () {
        return this._super();
    },

    /******************************************************************
     * 重载的接口
     ******************************************************************/

    getRoomConfig: function () {
        var cfg = this._super();
        cfg.MJsettlementWait = 0;
        cfg.destroyWaitTime = 120;
        return cfg;
    },

    getInfo: function () {
        var info = this._super();

        info.baoCard = this.baoCard;

        return info;
    },

    getRoundInfo: function () {
        var info = this._super();
        return info;
    },

    getReconnectInfo: function (rePlayer) {
        var info = this._super(rePlayer);
        info.baoCard = this.baoCard;

        return info;
    },

    onBeforeStartNewRound: function () {
        this._super();

    },

    onAfterStartNewRound: function () {
        this._super();
        this.preStartPlay();
    },

    preStartPlay: function () {

        var subConfig = this.getSubConfig();
        if(!subConfig.options.LaZhuang){
            this.startPlay();
        }
    },

    startPlay: function () {
        var card = {
            huncard: 0,
        }
        this._jingCard = this._publicCards.getCard();
        //this._jingCard = 37;
        var point = MJ.getPoint(this._jingCard);
        point += 1;
        if(point > 9){
            point = 1;
        }
        this.baoCard = MJ.getValue(MJ.getColor(this._jingCard),point);
        card.huncard = this.baoCard;
        this.initPlayersHandCards();
        this.broadcastReplay("onHunCard", card);
        var dealer = this.getDealerIndex();
        logger.debug("room=%d sendHangupTask in=WWMJ.startPlay", this.rid());
        this._sendHangupTask(this._startPlay);
    },

    _startPlay: function () {
        this._changeCurPlay(this.getDealerIndex());
        this._doCheckNewCardHangupTask();
    },

    onBeforePlayCard: function (player, msg, card) {
        var code = this._super(player, msg, card);
        if (code) {
            return code;
        }

        /*if(this._curTask == MJ.Task.CHI){
            if(card == player._chiCards[player._chiCards.length - 1].card){
                return SubCode.MJ_PLAY_FAILED;
            }
        }*/

        if (player.isBaoTing() && card != player.getLastCard()) { //天听不能换牌
            return SubCode.MJ_IS_BAOTING;
        }
        if (player._iskt && card != player.getLastCard()) { //扣听不能换牌
            return SubCode.MJ_IS_KOUTING;
        }

    },
    onAfterPlayCard: function (player, card, playInfo) {
        this._super(player, card, playInfo);

        if(player._isBaoTing){
            player._iskt = true;
            player.hunyou++;
            this.broadcastReplay("onPlayerHunyou", {
                playerIndex: player.getIndex(),
                hunYou: player.hunyou,
            });
        }
        player._hundiao = false;
        if( player._hundiao == false){
            if(player.checkHunDiao(player._handCards.getCards())){
                player._hundiao = true;
               /* player._iskt = true;
                var msg = {
                    playerIndex : 0,
                }
                msg.playerIndex = player.getIndex();
                this.broadcast('onPlayerKouTing',msg);*/
            }
        }
        this._playcard++;
    },

    checkNewCardHangupTask: function () {
        var player = this.getCurPlayer();
        var room = this;
        var huIndexs = [];
        var huPattern = player.checkHu();
        if (huPattern != Const.Pattern.NONE) {
            var rules = [];

            if (player.isFirstHand()) {
                if (player.getIndex() == this.getDealerIndex()) {
                    rules.push(Const.ScoreRule.TH);
                } else {
                    rules.push(Const.ScoreRule.DIHU);
                }
            }
            if (this.getCurGang()) {
                rules.push(Const.ScoreRule.GSH);
            }
            if (player._hundiao && player.getLastCard() == room.baoCard) {
                rules.push(Const.ScoreRule.HDH);
            }
            if (player._iskt) {
                rules.push(Const.ScoreRule.HunYou);
            }

            var card = player.getLastCard() || player.getInitLastCard();
            this._hangupTask.addHuTask(player.getIndex(), card, player.getIndex(), huPattern, rules);
            huIndexs.push(player.getIndex());
        }
        var gangArray = player.checkGang();
        if (gangArray.length > 0) {
            this._hangupTask.addGangTask(player.getIndex(), gangArray);
        }
        if(player._hundiao && player.hunyou == 0){
            this._hangupTask.addTingTask(player.getIndex(),[]);
        }

    },

    /*checkNewCardHangupTask: function() {
     var player = this.getCurPlayer();

     var huIndexs = [];
     var huPattern = player.checkHu();
     if (huPattern != Const.Pattern.NONE) {
     var rules = [];
     if (this.getCurGang()) {
     rules.push(Const.ScoreRule.GSH);
     }

     var card = player.getLastCard() || player.getInitLastCard();
     this._hangupTask.addHuTask(player.getIndex(), card, player.getIndex(), huPattern, rules);
     huIndexs.push(player.getIndex());
     }

     var gangArray = player.checkGang();
     if (gangArray.length > 0) {
     this._hangupTask.addGangTask(player.getIndex(), gangArray);
     }

     huIndexs.forEach(function(eIndex) {
     var ePlayer = this.getPlayerByIndex(eIndex);
     if (ePlayer && ePlayer.isBaoTing()) {
     this._hangupTask.submitTask(eIndex, MJ.Task.HU);
     }
     }.bind(this));
     },
     */

    checkPlayCardHangupTask: function (card) {
        var player = this.getCurPlayer();
        this._checkPlayCardHangupTask(card);

    },

    _checkPlayCardHangupTask: function (card) {
        var curPlay = this.getCurPlay();
        var nextIndex = this.getNextIndex(curPlay);
        var room = this;
        var curPlayer = this.getCurPlayer();
        if (!curPlayer.getLastCard() || curPlayer.getLastCard() != card) { // 不是打的上次摸的牌，则重新检查听牌
            //var tings = curPlayer.checkTing();
            //curPlayer.setTingCards(tings);
        }


        this.enumPlayers(function (eIndex, ePlayer) {
            if (eIndex != curPlay && !ePlayer.isRoundHu() && ePlayer._iskt == false) {
                var handCardsNum = ePlayer.getHandCardNum();
                var baoCard = ePlayer._handCards.getCardNum(room.baoCard);
                console.log("handCard = %d, baoCard = %d", handCardsNum, baoCard);
                if (ePlayer.checkPengWithCard(card) ) {
                    if(handCardsNum == 4 && baoCard == 2){
                    }else {
                        if(ePlayer._iskt == false){
                            this._hangupTask.addPengTask(eIndex, card, curPlay);
                        }
                    }

                }
                if (ePlayer.checkGangWithCard(card)) {
                    var gang = {
                        card: card,
                        from: curPlay,
                        gang: MJ.Gang.DIAN
                    };

                    if(card == this._jingCard){
                        gang.type = 6;
                        gang.gang = 6;
                    }
                    if(handCardsNum == 4 &&baoCard == 2 && card == this._jingCard){
                    }else{
                        this._hangupTask.addGangTask(eIndex, [gang]);
                    }
                }
                /*if (eIndex == nextIndex) { // 下家可以吃牌
                 var maxCards = ePlayer.checkChiWithCard(card);
                 if (maxCards) {
                 this._hangupTask.addChiTask(eIndex, card, curPlay, maxCards);
                 }
                 }*/
            }
        }.bind(this));
    },
    onAfterPengTask: function (player, card, pengTask) {

    },
    checkCurPlayHangupTask: function() {
        var player = this.getCurPlayer();

        var gangArray = player.checkGang();
        if (gangArray.length > 0) {
            this._hangupTask.addGangTask(player.getIndex(), gangArray);
        }
        this.onAfterNewCard();
    },
    onAfterGangTask: function (player, card, gangTask, gangInfo) {
        player._hundiao = false;
        if( player._hundiao == false){
            if(player.checkHunDiao(player._handCards.getCards())){
                player._hundiao = true;
            }
        }
    },
    checkGangHangupTask: function (playerIndex, gangInfo) {
        var card = gangInfo.card;
        if (gangInfo.type) {
            card = gangInfo.buCard;
        }

        var huIndexs = [];

        this.enumPlayers(function (eIndex, ePlayer) {
            if (eIndex != playerIndex && !ePlayer.isRoundHu() && !ePlayer.isPassHu() && ePlayer.getBaoTingPassHuTimes() < 1) {
                var huPattern = ePlayer.checkHuWithCard(card);
                if (huPattern != Const.Pattern.NONE) { // 抢杠
                    var rules = [];
                    var player = ePlayer;
                    var room = this;
                    rules.push(Const.ScoreRule.QG);
                    this._hangupTask.addHuTask(eIndex, card, playerIndex, huPattern, rules);
                    huIndexs.push(eIndex);
                }
            }
        }.bind(this));
    },

    checkGangNewCard: function (gangInfo) {
        if(gangInfo.type){
            return false
        }
        return true;
    },

    checkHuSettlement: function () {
        return true;
    },

    onSettlementHuTask: function (task) {
        var playerIndex = task.playerIndex;
        var pattern = task.pattern;
        var card = task.card;
        var from = task.from;
        var rules = task.rules;
        var huPlayer = this.getPlayerByIndex(playerIndex);
        if(pattern == Const.Pattern.HUNGANG){
            rules = [];
        }

        var isZM = (playerIndex == from); // 是否是自摸

        var targetsIndex = [];
        var targets = [];
        if (isZM) {
            this.enumPlayers(function (eIndex, ePlayer) {
                if (eIndex != playerIndex && !ePlayer.isRoundHu()) {
                    targetsIndex.push(eIndex);
                    targets.push(ePlayer);
                }
            });
        } else {
            huPlayer.addRoundItemScores(Const.ScoreRule.DH, Const.ItemScore[Const.ScoreRule.DH]);
            huPlayer.setRoundScoreRule(Const.ScoreRule.DH);
            targetsIndex.push(from);
            targets.push(this.getPlayerByIndex(from));
        }


        for (var i = 0; i < rules.length; ++i) {
            var rule = rules[i];
            switch (rule) {
                case Const.ScoreRule.QG:
                    if (!isZM) {
                        var targetPlayer = targets[0];
                        if (targetPlayer.getIndex() == this.getCurPlay() && this.getCurGang() > 0) { // 抢杠的被抢玩家一定是当前玩家
                            targetPlayer.setRoundScoreRule(rule);
                            targetPlayer.cancelLastGangForQG(card);
                        }
                    }
                    break;
                case Const.ScoreRule.GSP:
                    if (!isZM) {
                        var targetPlayer = targets[0];
                        targetPlayer.setLastGangUnscored();
                    }
                    break;
                default:
                    break;
            }
            huPlayer.setRoundScoreRule(rule);
            huPlayer.addRoundItemScores(rule, Const.ItemScore[rule]);
        }

        var patternScore = Const.PatternScore[pattern];
        var huResult = isZM ? MJ.Result.ZM : MJ.Result.DH;

        huPlayer.setRoundResult(huResult, targetsIndex, card);
        huPlayer.setRoundPattern(pattern, patternScore);

        this.broadcastReplay("onPlayerHu", {
            playerIndex: playerIndex,
            card: card,
            from: from,
        });
    },

    onSettlement: function () {
        if (this.isRoundHZ()) {
            this.enumPlayers(function (eIndex, ePlayer) {
                ePlayer._stat.LaZhuangScore = 0;
                ePlayer._selectLaZhuang = 0;
            }.bind(this));
            return;
        }
        this.enumPlayers(function (eIndex, ePlayer) {
            ePlayer.settlementGangScore();
        }.bind(this));

        this.enumPlayers(function (eIndex, ePlayer) {

            ePlayer.settlementRules();
        }.bind(this));

        this.enumPlayers(function (eIndex, ePlayer) {
            ePlayer.settlementPatternScore();
        }.bind(this));

        /*var DealerPlayer = this.getPlayerByIndex(this.getDealerIndex());
        if (this.isRoundHZ()) {
            this.enumPlayers(function (eIndex, ePlayer) {
                if (ePlayer == DealerPlayer) {
                    return;
                }else{
                    DealerPlayer.addRoundScore(1);
                    ePlayer.addRoundScore(-1);
                }
            });
        }*/
    },

    onCurRoundFinished: function () {
        this._super();
        // 计算新的庄家

        this._dealerIndex = this.getNextIndex(this._dealerIndex);
        this._dealerLZ = 1;

        this.broadcastReplay("onDealerChanged", {
            dealer: this._dealerIndex,
            dealerLZ: this._dealerLZ
        });
    },


    /******************************************************************
     * 消息处理
     ******************************************************************/

    /*handleSelectPiao: function(player, msg, callback) {
     if (!this.isPlaying()) {
     callback({code: Code.ROOM_NOT_PLAYING}); return;
     }

     if (!this.getOption("PIAO")) {
     callback({code: SubCode.PIAO_NOT_ALLOWED}); return;
     }

     if (player.isPiaoSelected()) {
     callback({code: SubCode.PIAO_STATUS_ERROR}); return;
     }

     var isPiao = msg.piao ? true : false;
     player.setPiao(isPiao);

     callback({});

     var isAllSelected = true;
     var results = {};
     this.enumPlayers(function(eIndex, ePlayer) {
     results[eIndex] = ePlayer.isPiao();
     if (!ePlayer.isPiaoSelected()) {
     isAllSelected = false;
     }
     });

     if (isAllSelected) {
     var msg = {"players": results};
     this.enumPlayers(function(eIndex, ePlayer) {
     ePlayer.send("onPlayerPiaoSelected", msg);
     }.bind(this));

     this._piaoStatus = Const.PiaoStatus.FINISHED;
     this.preStartPlay();
     }
     },*/
    //
    handleSelectLaZhuang: function (player, msg, callback) {
        if (!this.isPlaying()) {
            callback({code: Code.ROOM_NOT_PLAYING});
            return;
        }
        var subConfig = this.getSubConfig();
        if(!subConfig.options.LaZhuang){
            callback({code: SubCode.LZ_NOT_ALLOWED}); return;
        }
        if (player.isLaZhuangSelected()) {
            callback({code: SubCode.LZ_STATUS_ERROR});
            return;
        }
        if (msg.sroce == 0) {
            player._selectLaZhuang = 0;
        } else {
            player._selectLaZhuang = 1;
        }
        player._stat.LaZhuangScore = msg.sroce;

        var lazhuang = {
            playerIndex: 0,
            score: 0,
        };
        lazhuang.playerIndex = player._index;
        lazhuang.score = msg.sroce;
        this.broadcastReplay("onSelectLaZhuang", lazhuang);
        callback({});

        var isAllSelected = true;
        var DealerIndex = this.getDealerIndex();
        this.enumPlayers(function(eIndex, ePlayer) {
            if (!ePlayer.isLaZhuangSelected()) {
                if(DealerIndex != eIndex){
                    isAllSelected = false;
                }
            }
        });
        if (isAllSelected) {
            this.startPlay();
        }
    },


    /******************************************************************
     * 功能接口
     ******************************************************************/

    /**
     * 结算玩家是否听牌
     * @param player
     * @private
     */
    _settlementPlayerTing: function (player) {
        //已听牌玩家不用再检测
        if (player.isRoundTing()) {
            return;
        }

        // 对未胡牌的玩家检查是否听牌
        var tings = player.checkTing();
        var pattern = Const.Pattern.NONE;
        var patternScore = 0;
        for (var i = 0; i < tings.length; ++i) {
            var ting = tings[i];
            var score = Const.PatternScore[ting.pattern];
            if (score > patternScore) {
                pattern = ting.pattern;
                patternScore = score;
            }
        }

        player.setRoundPattern(pattern, 0);
    },
    //随机获取一张牌
    getRandomCard: function () {
        var index = ExNumber.rand(this._publicCards.cards.length - 1);
        var card = this._publicCards.cards[index];
        return card;
    },
    //获取玩家宝牌数量
    getBaoCardNum: function (player) {
        return player._handCards.getCardNum(this.baoCard);
    },
    //计算牌


});